package com.itheima.reggie.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.EmployeeDto;
import com.itheima.reggie.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    //用于完成用户登录的方法
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {
        if (employee == null
                || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("用户名或密码不能为空");
        }
        //查询数据库 select * from employee where username=?
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee existEmp = employeeService.getOne(qw);
        if (existEmp == null) {
            return R.error("账号不存在");
        }
        //数据库的Employee<密文> 和用户输入的<明文>比较 密文比较
        String password = existEmp.getPassword();//密文
        String password1 = employee.getPassword();//明文
        password1 = DigestUtils.md5DigestAsHex(password1.getBytes());
        if (password.equals(password1)) {
            //对比成功,返回code:1 和data(用户信息).
            // 将用户数据存入会话中<session> 如何获取session!
            session.setAttribute("loginUser", existEmp);
            existEmp.setPassword(null); //将密码设为空
            return R.success(existEmp);
        }
        return R.error("用户名或密码错误!");
        //对比失败,返回code 0 和msg 用户名或密码错误 Filter HandlerInterceptor
    }


    @PostMapping("/logout")
    public R logout(HttpSession httpSession) {
        //清理Session中保存的当前登录员工的ID
        httpSession.removeAttribute("loginUser");
        return R.success(null);
    }
    @PostMapping
    public R addEmployee(@RequestBody Employee employee, HttpSession session) {
        //0.检查数据,哪些是需要处理的
        //0.1: 密码使用默认的123456,需要加密 DigestUtils.md5DigestAsHex
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        //0.2:status 不需要处理,数据库默认是1
        //0.3:creat_time和 update_time,设置为当前系统时间
        employee.setPassword(password);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //0.4:creat_user 和update_user 创建人和修改人,应该是当前登录人
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        employee.setCreateUser(loginUser.getId());
        employee.setUpdateUser(loginUser.getId());
        // 1.调用业务层保存 employee 数据
        boolean save = employeeService.save(employee);
        //2.返回结果R
        if (save){
            return R.success(null);
        }else {
            return R.error("保存失败");
        }

    }

    @GetMapping("/page")
    public R pageQuery(Integer page,Integer pageSize, String name){
        //进行带条件分页查询
        IPage<Employee> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        //封装查询条件
        if(StringUtils.isNotEmpty(name)){
            qw.like(Employee::getName,name);
        }
        qw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,qw);
        //通过pageInfo获取分页结果 list<>集合  总记录数
        List<Employee> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        System.out.println(total);
        Map data = new HashMap<>();
        data.put("records",records);
        data.put("total",(int)total);
        return R.success(data);
    }
    //更改员工状态
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
//        log.info(employee.toString());
//        Long empId = (Long)request.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
        boolean b = employeeService.updateById(employee);
        if (b){
            return R.success(null);
        }
        return R.error("修改失败");
    }

    //根据id查询员工信息
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }
    //导出员工数据
    @GetMapping("/export")
    public void exportEmployee(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition",
                "attachment; filename=employee.xlsx");
        List<Employee> list = employeeService.list();
        List<EmployeeDto> employeeStrList = new ArrayList<>();
        for (Employee employee : list) {
            EmployeeDto employeeStr = new EmployeeDto();
            BeanUtils.copyProperties(employee,employeeStr);

            String s = employee.getId().toString();
            employeeStr.setIdStr(s);
            Integer status = employee.getStatus();
            if (status == 1) {
                employeeStr.setStatusStr("在职");
            }else {
                employeeStr.setStatusStr("离职");
            }
            String sex = employee.getSex();
            if ("0".equals(sex)) {
                employeeStr.setSex("女");
            } else {
                employeeStr.setSex("男");
            }
            Employee byId = employeeService.getById(employee.getCreateUser());
            employeeStr.setCreateUserStr(byId.getName());
            employeeStr.setUpdateUserStr(byId.getName());
            employeeStrList.add(employeeStr);
        }
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream,EmployeeDto.class).sheet("员工数据").doWrite(employeeStrList);
    }
}


